const User = require('../models/user');
const bcrypt = require('bcryptjs');
const Role = require('../models/role');
/**
 * 获取所有用户
 * @param {number} page 页码
 * @param {number} pageSize 每页条数
 * @param {string} searchKey 搜索关键词
 * @returns {Promise<Array>} 
 */

const getUsers = async ({page, pageSize, searchKey = ''}) => {
    try {
        const list = await User.find({
            $or: [
                { name: { $regex: searchKey, $options: 'i' } },
                { email: { $regex: searchKey, $options: 'i' } },
                { phone: { $regex: searchKey, $options: 'i' } },
            ]
        }).skip((page - 1) * pageSize).limit(pageSize).exec();
        const total = await User.countDocuments({
            $or: [
                { name: { $regex: searchKey, $options: 'i' } },
                { email: { $regex: searchKey, $options: 'i' } },
                { phone: { $regex: searchKey, $options: 'i' } },
            ]
        });
        const newList = list.map(async item => {
            const role = await Role.findById(item.role);
            return {
                id: item._id,
                name: item.name,
                email: item.email,
                phone: item.phone,
                role: item.role,
                roleName: role.name? role.name : '未知角色',
                active: item.active,
                remark: item.remark,
                createdAt: item.createdAt,
                avatar: item.avatar,
            };
        })
        return {
            data:{
                list:await Promise.all(newList),
                total,
            },
            code:200,
            message:'获取用户列表成功'
        };
    }
    catch (error) {
        return {
            code:400,
            message:'获取用户列表失败: ' + error.message
        };
    }
}

/**
 * 新增用户
 * @param {Object} userData 
 * @returns {Promise<Object>} 
 */

const addUser = async (userData, createBy = '') => {
    try {
        const hashedPassword = await bcrypt.hash(userData.password, 10);
        const newUser = await User.create({...userData, password: hashedPassword, createBy, updateBy: createBy });

        return newUser
    }
    catch (error) {
        return error.message;
    }
}
/**
 * @description: 批量新增用户
 * @param {*} userDataList 包含用户列表的请求对象
 * @return {*}
 */
const batchAddUser = async (userDataList, createBy = '') => {
    
    try {
        if(!userDataList || userDataList.length === 0) {
            return {
                code:201,
                message:'用户列表不能为空'
            };
        }
        
        // 处理重复
        const emailList = userDataList.map(item => item.email);
        // 判断是否有重复邮箱
        const uniqueEmailList = [...new Set(emailList)];
        if(emailList.length !== uniqueEmailList.length) {
            return {
                code:201,
                message:'文档内存在重复邮箱，请检查重新上传'
            };
        }

        // 判断是否有admin角色
        if(emailList.some(item => item.email === 'admin')) {
            return {
                code:201,
                message:'不能新增admin用户'
            };
        }

        // 判断是否为邮箱
        if(!emailList.every(item => /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(item))) {
            return {
                code:201,
                message:'邮箱格式错误'
            };
        }
        const existUserList = await User.find({ email: { $in: emailList } });
        if (existUserList.length > 0) {
            return {
                code:201,
                message:'用户已存在，请检查重新上传'
            };
        }
    
        const newUserDataList = await Promise.all(
            userDataList.map(async (item) => {
                const role = await Role.findOne({ name: item.role });
                const newPassword = await bcrypt.hash(String(item.password), 10);
                return {
                    ...item,
                    role: role? role._id : null,
                    password: newPassword,
                    createBy: createBy,
                    updateBy: createBy,
                    active: true
                }
            })
        );
        await User.insertMany(newUserDataList);
        return {
            code:200,
            message:'新增成功'
        };
    }
    catch (error) {
        return {
            code:400,
            message:error.message
        };
    }

}

/**
 * 删除用户
 * @param {string} userId 用户id
 * @returns {Promise<string>} 
 */
const deleteUser = async (userId) => {
    try {
        const result = await User.findByIdAndDelete(userId);
        if (result) {
            return {
                code:200,
                message:'删除成功'
            };
        }
        else {
            return {
                code:201,
                message:'用户不存在'
            };
        }
    }
    catch (error) {
        return {
            code:400,
            message:error.message
        };
    }
}
/**
 * 批量删除用户
 * @param {Array} userIdList 用户id列表
 * @returns {Promise<string>} 
 */
const batchDeleteUser = async (userIdList) => {
    try {
        const result = await User.deleteMany({ _id: { $in: userIdList } });
        if (result.deletedCount > 0) {
            return {
                code:200,
                message:'删除成功'
            };
        }
        else if (result.deletedCount === 0) {
            return {
                code:201,
                message:'用户不存在'
            };
        }
        else {
            return {
                code:400,
                message:'删除失败'
            };
        }

    }
    catch (error) {
        return {
            code:400,
            message:error.message
        };
    }
}

/**
 * @description: 更新用户
 * @param {*} userId 用户id
 * @param {*} userData 更新数据
 * @return {*}
 */
const updateUser = async (userId, userData) => {
    try {
        if (userData.password!=='') {
            userData.password = bcrypt.hashSync(userData.password, 10);
        } else {
            userData.password = User.findById(userId).password;
        }
        if (userData.phone) {
            userData.phone = userData.phone.replace(/\D/g, '');
        }
        const newUserData = {...userData };
        const result = await User.findByIdAndUpdate(userId, newUserData);
        if (result) {
            return {
                code:200,
                message:'更新成功'
            };
        }
        else {
            return {
                code:201,
                message:'用户不存在'
            };
        }
    }
    catch (error) {
        return {
            code:400,
            message:error.message
        };
    }
}
/**
 * @description: 批量更新用户
 * @param {Array} userIdList 用户id
 * @param {String} updateParam 修改的字段
 * @param {*} updateValue
 * @return {*}
 */

const batchUpdateUser = async (userIdList, updateParam,updateValue) => {
    try {
        // 批量更新用户某个属性
        const result = await User.updateMany({ _id: { $in: userIdList } }, { $set: {[updateParam]:updateValue} });
        if (result.modifiedCount > 0) {
            return {
                code:200,
                message:'更新成功'
            };
        }
        else if (result.modifiedCount === 0) {
            return {
                code:201,
                message:'用户不存在'
            };
        }
        else {
            return {
                code:400,
                message:'更新失败'
            };
        }
    }
    catch (error) {
        return {
            code:400,
            message:error.message
        };
    }

}

module.exports = { 
    addUser,
    getUsers,
    batchAddUser,
    deleteUser,
    batchDeleteUser,
    updateUser,
    batchUpdateUser
};